using System;
using System.Collections.Generic;
using System.Linq;

namespace LDNS.Models
{
    /// <summary>
    /// DNS缓存项模型
    /// 作者：huobing
    /// </summary>
    public class DnsCacheItem
    {
        /// <summary>
        /// 域名
        /// </summary>
        public string Domain { get; set; } = string.Empty;
        
        /// <summary>
        /// 解析的IP地址（单个IP，用于向后兼容）
        /// </summary>
        public string IP 
        { 
            get => IPs?.FirstOrDefault() ?? string.Empty; 
            set 
            {
                if (IPs == null)
                    IPs = new List<string>();
                
                if (!string.IsNullOrEmpty(value))
                {
                    IPs.Clear();
                    IPs.Add(value);
                }
            }
        }
        
        /// <summary>
        /// 解析的所有IP地址列表
        /// </summary>
        public List<string> IPs 
        { 
            get => _ips ?? (_ips = new List<string>()); 
            set 
            {
                if (value != null)
                {
                    // 在设置IP列表时进行去重
                    _ips = value.Distinct().ToList();
                }
                else
                {
                    _ips = new List<string>();
                }
            }
        }
        
        /// <summary>
        /// IP地址列表的私有字段
        /// </summary>
        private List<string>? _ips;
        
        /// <summary>
        /// 记录类型
        /// </summary>
        public string RecordType { get; set; } = "A";
        
        /// <summary>
        /// 生存时间（秒）
        /// </summary>
        public int Ttl { get; set; } = 3600;
        
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 最后访问时间
        /// </summary>
        public DateTime LastAccessed { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpiresAt => CreatedTime.AddSeconds(Ttl);
        
        /// <summary>
        /// 是否已过期
        /// </summary>
        public bool IsExpired => DateTime.Now > ExpiresAt;
        
        /// <summary>
        /// 查询次数
        /// </summary>
        public int QueryCount { get; set; } = 0;
        
        /// <summary>
        /// 数据来源（缓存/上游/手动）
        /// </summary>
        public string Source { get; set; } = "upstream";
        
        /// <summary>
        /// 上游DNS服务器IP地址
        /// </summary>
        public string? UpstreamDns { get; set; } = null;
    }
}